//
//  ZYFDataManager.m
//  ihome
//
//  Created by xl on 2017/10/21.
//  Copyright © 2017年 Yvan. All rights reserved.
//

#import "ZYFDataManager.h"
 
//#import <AFNetworking.h>


static ZYFDataManager *dataManager = nil;
static AFHTTPSessionManager *afnManager = nil;
static NSTimeInterval timeoutNum = 60*20;




@interface ZYFDataManager()<NSXMLParserDelegate>
// 假设有一个AFHTTPSessionManager实例叫做yourHTTPSessionManager
// 和一个NSMutableArray来跟踪所有的上传任务
// 
//@property (nonatomic, strong) AFHTTPSessionManager *yourHTTPSessionManager;
@property (nonatomic, strong) NSMutableArray *uploadTasks;

@property (nonatomic, strong) NSMutableString *currentElementValue;

@end

@implementation ZYFDataManager{
    CGFloat pro;
}



/**
 *  创建网络请求类的单例
 */
+ (ZYFDataManager *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataManager = [[ZYFDataManager alloc]init];
        //创建网络请求管理对象
        [dataManager changeBaseUrlAction];
    });
    return dataManager;
}

-(void)changeBaseUrlAction{
    afnManager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:API_BASEURL]];//API_BASEURL_pslV5
    
    //申明请求的数据是json类型
    afnManager.requestSerializer = [AFJSONRequestSerializer serializer];
//    [afnManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    afnManager.requestSerializer.accessibilityTextualContext
    //申明返回的结果是二进制类型
    afnManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    afnManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/x-www-form-urlencoded", @"text/json", @"text/javascript", @"text/html", @"text/plain",@"multipart/form-data",@"image/png",@"application/pdf",@"application/octet-stream",@"application/msword",@"image/jpeg",@"message/rfc822",@"multipart/alternative",@"application/vnd.openxmlformats-officedocument.wordprocessingml.document",@"application/vnd.ms-excel",@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",@"application/x-gtar",@"application/x-gzip",@"application/java-archive",@"application/vnd.ms-powerpoint",@"application/vnd.openxmlformats-officedocument.presentationml.presentation",@"application/vnd.ms-works",@"application/x-compress",@"application/x-zip-compressed",@"image/gif", nil];
    
//    AFHTTPSessionManager * apiManager = [AFHTTPSessionManager initWithBaseURL:[NSURL URLWithString:baseURL];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    policy.allowInvalidCertificates = YES;
    afnManager.securityPolicy = policy;
    
    afnManager.securityPolicy.allowInvalidCertificates = NO;
    
//    AFHTTPSessionManager * apiManager = [AFHTTPSessionManager initWithBaseURL:[NSURL URLWithString:baseURL];
//    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//    policy.allowInvalidCertificates = YES;
//    apiManager.securityPolicy = policy;
    
    
//    // /先导入证书
//      NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"hgcang" ofType:@"cer"];//证书的路径
//      NSData *certData = [NSData dataWithContentsOfFile:cerPath];
//
//      // AFSSLPinningModeCertificate 使用证书验证模式
//      AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//
//      // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
//      // 如果是需要验证自建证书，需要设置为YES
//      securityPolicy.allowInvalidCertificates = YES;
//
//      //validatesDomainName 是否需要验证域名，默认为YES；
//      //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
//      //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
//      //如置为NO，建议自己添加对应域名的校验逻辑。
//      securityPolicy.validatesDomainName = NO;
//
//      securityPolicy.pinnedCertificates = @[certData];
//
//      return securityPolicy;
}


-(void)setHttpsFileWithURL:(NSString *)urlStr{
//    if ([urlStr containsString:@"https://gateway.xiaohongyi.net"]) {
//        NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"*.h5.huaniupp.com" ofType:@"cer"];
//        NSData *certData = [NSData dataWithContentsOfFile:cerPath];
//        NSSet *dataSet = [NSSet setWithArray:@[certData]];
//        afnManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:dataSet];
//        afnManager.securityPolicy.allowInvalidCertificates = YES;
//        [afnManager.securityPolicy setValidatesDomainName:NO];
//        //关闭缓存避免干扰测试
//        afnManager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
//    }
}

/**
 *  封装AFN的Download
 *
 *  @param URLString 网络请求地址
 *  @param dict      参数(可以是字典或者nil)
 *  @param succeed   成功后执行success block
 *  @param failure   失败后执行failure block
 */
- (void)downloadFile:(NSString *)URLString dict:(id)dict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
    afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
    
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    if (token) {
//        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
    }else{
        if([SSUserManager sharedUser].userModel.tempToken){
            token = [SSUserManager sharedUser].userModel.tempToken;
//            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
//
//            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
        }
    }
    [headerDic setValue:token forKey:@"Authorization"];
    
    
    
    NSString *fileName = [NSString stringWithFormat:@"%@",dict[@"name"]];
    [afnManager GET:URLString parameters:@{} headers:headerDic progress:^(NSProgress * _Nonnull downloadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
//        NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        [self successHandling:responseObject requestUrl:tempURL];
        succeed(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self exceptionHandling:task error:error];
        NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
        NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
        failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
    }];
}

/**
 *  封装AFN的GET请求
 *
 *  @param URLString 网络请求地址
 *  @param dict      参数(可以是字典或者nil)
 *  @param succeed   成功后执行success block
 *  @param failure   失败后执行failure block
 */
- (NSURLSessionDataTask *)GET:(NSString *)URLString dict:(id)dict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure
{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
    afnManager.requestSerializer = [AFJSONRequestSerializer serializer];
    afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
//    [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];

    NSString *sdkAppStrUrl = [NSString stringWithFormat:@"%@%@",API_BASEURLmall219,API_tencentAppInfo];
    if(![URLString isEqualToString:sdkAppStrUrl]){
        NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
        if (token) {
    //        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
    ////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
        }else{
            if([SSUserManager sharedUser].userModel.tempToken){
                token = [SSUserManager sharedUser].userModel.tempToken;
    //            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
    //
    //            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
            }
        }
        NSLog(@"token==%@\n",token);
        [headerDic setValue:token forKey:@"Authorization"];
    }
    
    NSURLSessionDataTask *tempDataTask =[afnManager GET:URLString parameters:dict headers:headerDic progress:^(NSProgress * _Nonnull downloadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        [self successHandling:jsonData requestUrl:tempURL];
        succeed(jsonData);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self exceptionHandling:task error:error];
        NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
        NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
        failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
    }];
    return tempDataTask;
}

/**
 *  封装AFN的DELETE请求
 *
 *  @param URLString 网络请求地址
 *  @param dict      参数(可以是字典或者nil)
 *  @param succeed   成功后执行success block
 *  @param failure   失败后执行failure block
 */
- (void)DELETE:(NSString *)URLString parameters:(id)dict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure
{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
    afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
//    [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    if (token) {
//        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
    }else{
        if([SSUserManager sharedUser].userModel.tempToken){
            token = [SSUserManager sharedUser].userModel.tempToken;
//            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
//
//            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
        }
    }
    [headerDic setValue:token forKey:@"Authorization"];
    [afnManager DELETE:URLString parameters:dict headers:headerDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        [self successHandling:jsonData requestUrl:tempURL];
        succeed(jsonData);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self exceptionHandling:task error:error];
        NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
        NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
        failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
    }];
}

/**
 *  封装AFN的PUT请求
 *
 *  @param URLString 网络请求地址
 *  @param dict      参数(可以是字典或者nil)
 *  @param succeed   成功后执行success block
 *  @param failure   失败后执行failure block
 */
- (void)PUT:(NSString *)URLString parameters:(id)dict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure
{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
    afnManager.requestSerializer.timeoutInterval = 300;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
//    [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    if (token) {
//        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
    }else{
        if([SSUserManager sharedUser].userModel.tempToken){
            token = [SSUserManager sharedUser].userModel.tempToken;
//            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
//
//            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
        }
    }
    [headerDic setValue:token forKey:@"Authorization"];

    [afnManager PUT:URLString parameters:dict headers:headerDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        [self successHandling:jsonData requestUrl:tempURL];
        succeed(jsonData);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self exceptionHandling:task error:error];
        NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
        NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
        failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
    }];
}

/**
 *  封装AFN的POST请求
 *
 *  @param URLString 网络请求地址
 *  @param dict      参数(可以是字典或者nil)
 *  @param succeed   成功后执行success block
 *  @param failure   失败后执行failure block
 */
- (NSURLSessionDataTask *)POST:(NSString *)URLString dict:(id)dict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure
{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
     afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
    
    NSString *tempStr22 = [NSString stringWithFormat:@"%@%@",touristsRegister_BASEURL,API_wxloginVerify_URL];
        
    NSString *tempsUrlStirng = [NSString stringWithFormat:@"%@%@",API_BASEURL,API_checkUserVersion];
    
    NSString *API_forgotPasswordStirng = [NSString stringWithFormat:@"%@%@",API_writemallForgotPasswordBaseURL,API_forgotPassword];
    
    if(![tempsUrlStirng isEqualToString:URLString]){
        if([URLString containsString:@"http://office.creword.com//oauthapi/oauth/token"]||
           [URLString containsString: @"http://office.creword.com//oauthapi/user/getMobileAchCaptchas"]||
           [URLString containsString:getVertificationCode_BASEURL]||
           [URLString containsString:@"http://antiplagiarize-api.writemall.com/card/bind/3DaysPLUSCard"]||[URLString containsString:tempStr22]||[URLString isEqualToString:API_forgotPasswordStirng]){// 登录时进入  扫码微信登录时 设置基本token
            [headerDic setValue:@"Basic Y2xpZW50LWFwOjFxYXp4c3cy" forKey:@"Authorization"];
        }
        else{
            
    //        [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
            NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
            if (token) {
        //        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
        ////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
            }else{
                if([SSUserManager sharedUser].userModel.tempToken){
                    token = [SSUserManager sharedUser].userModel.tempToken;
        //            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
        //
        //            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
                }
            }
            [headerDic setValue:token forKey:@"Authorization"];
            
            [self wqWriteData:[NSString stringWithFormat:@"tokennnnn==%@",token] withFileName:@"ttttttkkkkkkkkkkkkkkkkenName"];
        }
        
        

    }
    else{
        
    }
    
    
    afnManager.requestSerializer =  [AFJSONRequestSerializer serializer];
    NSURLSessionDataTask *sessionDataTask =[afnManager POST:URLString parameters:dict headers:headerDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        [self successHandling:jsonData requestUrl:tempURL];
        succeed(jsonData);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self exceptionHandling:task error:error];
        NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
        NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
        failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
    }];
    return sessionDataTask;
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString fileArr:(NSArray*)fileArr succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
     afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
//    [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    if (token) {
//        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
    }else{
        if([SSUserManager sharedUser].userModel.tempToken){
            token = [SSUserManager sharedUser].userModel.tempToken;
//            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
//
//            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
        }
    }
    [headerDic setValue:token forKey:@"Authorization"];

    NSURLSessionDataTask *tempTask =[afnManager POST:URLString parameters:@{@"text":@"text"} headers:headerDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //根据当前系统时间生成图片名称
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:date];
        for (int i = 0; i < fileArr.count; i++) {
            NSString *fileNmae = [NSString stringWithFormat:@"%@%d.png",dateString,i];
            id tempFileData = fileArr[i];
            
            NSData *imageData = tempFileData;
            if([tempFileData isKindOfClass:[UIImage class]]){
                imageData = [self fileData:tempFileData];
            }
            
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileNmae mimeType:@"application/octet-stream"];
        }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            double completedCount = uploadProgress.completedUnitCount;
            double totalCount = uploadProgress.totalUnitCount;
            if (completedCount/totalCount > 0.99f) {
                //NSLog(@"上传完成");
            }else{
                //NSLog(@"上传进度 %.2lf",completedCount/totalCount*100);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
            NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
            [self successHandling:jsonData requestUrl:tempURL];
            succeed(jsonData);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self exceptionHandling:task error:error];
            NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
            NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
            failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
        }];
    
    return tempTask;
}




- (void)POST:(NSString *)URLString contentType:(NSString *)contentTypeStr fileArr:(NSArray*)fileArr parameterDictionay:(NSDictionary *)parameterDict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
     afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
    
    if(contentTypeStr){//@"application/x-www-form-urlencoded"
        [afnManager.requestSerializer setValue:contentTypeStr forHTTPHeaderField:@"Content-Type"];
    }
    else{
        afnManager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    
    NSString *tempStr22 = [NSString stringWithFormat:@"%@%@",touristsRegister_BASEURL,API_wxloginVerify_URL];
    NSString *tempStrAPI_oauthToken_URL = [NSString stringWithFormat:@"%@%@",touristsRegister_BASEURL,API_oauthToken_URL];
    if([URLString containsString:@"http://antiplagiarize-api.writemall.com/card/bind/3DaysPLUSCard"]||[URLString containsString:tempStr22]||[URLString containsString:tempStrAPI_oauthToken_URL]){
        
        //设置基本token
        [headerDic setValue:@"Basic Y2xpZW50LWFwOjFxYXp4c3cy" forKey:@"Authorization"];
    }
    else{
//        [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
        NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
        if (token) {
    //        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
    ////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
        }else{
            if([SSUserManager sharedUser].userModel.tempToken){
                token = [SSUserManager sharedUser].userModel.tempToken;
    //            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
    //
    //            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
            }
        }
        [headerDic setValue:token forKey:@"Authorization"];
    }
    

    [afnManager POST:URLString parameters:parameterDict headers:headerDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //根据当前系统时间生成图片名称
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:date];
        for (int i = 0; i < fileArr.count; i++) {
            NSString *fileNmae = [NSString stringWithFormat:@"%@%d.png",dateString,i];
            NSData *tempFileData = fileArr[i];
            NSData *imageData = tempFileData;
            if([tempFileData isKindOfClass:[UIImage class]]){
                imageData = [self fileData:tempFileData];
            }
            
            
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileNmae mimeType:@"application/octet-stream"];
        }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            double completedCount = uploadProgress.completedUnitCount;
            double totalCount = uploadProgress.totalUnitCount;
            if (completedCount/totalCount > 0.99f) {
                //NSLog(@"上传完成");
            }else{
                //NSLog(@"上传进度 %.2lf",completedCount/totalCount*100);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            NSString *requestStr1 = [NSString stringWithFormat:@"%@%@",API_Cloud_BASEURL,API_htmlToWordDownloadURL];
            NSString *requestStr2 = [NSString stringWithFormat:@"%@%@",API_Cloud_BASEURL,API_htmlToPdfDownloadURL];
            if([URLString isEqualToString:requestStr1]||
               [URLString isEqualToString:requestStr2])
            {
                
                if(responseObject){
                    succeed(@{@"code":@"200",@"data":responseObject,@"message":@""});
                }
                else{
                    succeed(@{@"code":@"200",@"data":@{},@"message":kLocalizedString(@"数据返回有误")});
                }
            }
            else{
                afnManager.requestSerializer = [AFJSONRequestSerializer serializer];
                
                NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
                NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
                [self successHandling:jsonData requestUrl:tempURL];
                succeed(jsonData);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            afnManager.requestSerializer = [AFJSONRequestSerializer serializer];
            
            
            [self exceptionHandling:task error:error];
            NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
            NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
            failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
            
            
        }];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString fileArr:(NSArray*)fileArr parameterDictionay:(NSDictionary *)parameterDict succeed:(void (^)(id data))succeed failure:(void (^)(NSDictionary *error))failure{
    __block NSString *tempURL = URLString;
    [self setHttpsFileWithURL:URLString];
     afnManager.requestSerializer.timeoutInterval = timeoutNum;
    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
    
    
    if([URLString containsString:@"http://antiplagiarize-api.writemall.com/card/bind/3DaysPLUSCard"]){
        
        //设置基本token
        [headerDic setValue:@"Basic Y2xpZW50LWFwOjFxYXp4c3cy" forKey:@"Authorization"];
    }
    else{
//        [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
        NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
        if (token) {
    //        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
    ////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
        }else{
            if([SSUserManager sharedUser].userModel.tempToken){
                token = [SSUserManager sharedUser].userModel.tempToken;
    //            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
    //
    //            [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
            }
        }
        [headerDic setValue:token forKey:@"Authorization"];
    }
    NSLog(@"666---headerDic.description==%@\n",headerDic.description);
    NSLog(@"666---headerDic.description==%@\n",headerDic);

    NSURLSessionDataTask *tempTask = [afnManager POST:URLString parameters:parameterDict headers:headerDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //根据当前系统时间生成图片名称
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:date];
        for (int i = 0; i < fileArr.count; i++) {
            NSString *fileNmae = [NSString stringWithFormat:@"%@%d.png",dateString,i];

            NSData *tempFileData = fileArr[i];
            NSData *imageData = tempFileData;
            if([tempFileData isKindOfClass:[UIImage class]]){
                imageData = [self fileData:tempFileData];
            }
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileNmae mimeType:@"application/octet-stream"];
        }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            double completedCount = uploadProgress.completedUnitCount;
            double totalCount = uploadProgress.totalUnitCount;
            if (completedCount/totalCount > 0.99f) {
                //NSLog(@"上传完成");
            }else{
                //NSLog(@"上传进度 %.2lf",completedCount/totalCount*100);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"jsonStr==%@\n",jsonStr);
            NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
            NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
            
            BOOL IsFinalKeyString = NO;
            NSMutableArray *finalKeyMarr;
            if([jsonData isKindOfClass:[NSDictionary class]]){
                if([jsonData[@"data"] isKindOfClass:[NSDictionary class]]){
                    NSDictionary *tempDict = jsonData[@"data"];
                    if(tempDict.allKeys.count>0){
                        
                        finalKeyMarr = [[NSMutableArray alloc] initWithCapacity:tempDict.allKeys.count];
                        
                        NSArray *tempJsonArr = [jsonStr componentsSeparatedByString:@"\"data\":{\""];
                        if(tempJsonArr.count==2){
                            NSString *lastJsonStr = tempJsonArr.lastObject;
                            NSString *lastJsonStr22 = [NSString stringWithFormat:@"}],\"%@",lastJsonStr];
                            
                            
                            NSArray *tempJsonArrFinal = [lastJsonStr22 componentsSeparatedByString:@"}],\""];
                            
                            for (NSString *finalDianStr in tempJsonArrFinal) {
                                NSArray *tempJsonArrFinalArray2 = [finalDianStr componentsSeparatedByString:@":"];
                                if(tempJsonArrFinalArray2.count>=2){
                                    NSString *finalKeyString = tempJsonArrFinalArray2.firstObject;
                                    
//                                    ",
                                    NSString *finalKeyString2 = [finalKeyString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
                                    NSString *finalKeyString3 = [finalKeyString2 stringByReplacingOccurrencesOfString:@"," withString:@""];
                                    NSLog(@"finalKeyString3==%@\n",finalKeyString3);
                                    [finalKeyMarr addObject:finalKeyString3];
                                }
                            }
                            
                            if(finalKeyMarr.count==tempDict.allKeys.count){
                                IsFinalKeyString = YES;
                            }
                        }
                    }
                }
            }
            
            
            
            [self successHandling:jsonData requestUrl:tempURL];
            NSLog(@"finalKeyMarr==%@\n",finalKeyMarr);
            if(!IsFinalKeyString){
                succeed(jsonData);
            }
            else{
                
                NSMutableDictionary *tempMdict = [NSMutableDictionary dictionaryWithDictionary:jsonData];
                tempMdict[@"CWKeyArray"] = [[NSArray alloc] initWithArray:finalKeyMarr];
                succeed([NSDictionary dictionaryWithDictionary:tempMdict]);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self exceptionHandling:task error:error];
            NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
            NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
            failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
        }];
    
    return tempTask;
}
-(void)successHandling:(NSDictionary*)resDic requestUrl:(NSString*)urlStr{
    if ([resDic objectForKey:@"code"] == nil) {
        
        return;
    }
    if ([[resDic objectForKey:@"code"] integerValue] == 200) {
        
    }else if([[resDic objectForKey:@"code"] integerValue] == 401){
        
        [self appRootJumpLoginViewControllerWithStatuCodeNumber:401];
        
       

    }else{
        NSLog(@"%@ \n %@",urlStr,resDic);
        NSString *messageStr = [NSString stringWithFormat:@"%@",[resDic objectForKey:@"message"]];
        
    }
}

-(void)exceptionHandling:(NSURLSessionDataTask *_Nullable)task error:(NSError * _Nonnull)error{
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
    NSInteger statusCode = response.statusCode;
    NSDictionary *allHeaders = response.allHeaderFields;
    if (statusCode == 401) {
        
        [self appRootJumpLoginViewController:401];
    }else{
        [self appRootJumpLoginViewController:0];
    }
//    NSLog(@"加载失败,请稍后重试 \n接口状态:%zd \n接口headers:%@",statusCode,allHeaders);
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        return nil;
    }
    return dic;
}

- (void)appRootJumpLoginViewController:(NSInteger)statusCode{
    [dataManager cancelAllOperations];
//
    
    if(statusCode==401){
        NSLog(@"您的账号在其他地方登录,如果不是本人操作请重置账号密码222");
        return;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:kLocalizedString(@"温馨提示") message:kLocalizedString(@"您的账号在其他地方登录,如果不是本人操作请重置账号密码") preferredStyle:UIAlertControllerStyleAlert];
        XSWeakSelf;
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            [weakSelf createUserTempData];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [(KAppDelegate) showLoginViewController];
//            });
#warning [(KAppDelegate) showLoginViewController];
#warning [(KAppDelegate) showLoginViewController];
#warning [(KAppDelegate) showLoginViewController];
#warning [(KAppDelegate) showLoginViewController];
#warning [(KAppDelegate) showLoginViewController];
#warning [(KAppDelegate) showLoginViewController];
        }];
//                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:confirm];
        //            [alert addAction:cancel];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[YSHelp getCurrentVC] presentViewController:alert animated:YES completion:nil];
        });
    }
    else{
//        [(KAppDelegate) showLoginViewController];
    }
    
}
// statuCodelNum 401 token过期
- (void)appRootJumpLoginViewControllerWithStatuCodeNumber:(NSInteger)statuCodelNum{
    [dataManager cancelAllOperations];
   
    if(statuCodelNum==401){
        NSLog(@"您的账号在其他地方登录,如果不是本人操作请重置账号密码333");
        //return;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:kLocalizedString(@"温馨提示") message:kLocalizedString(@"您的账号在其他地方登录,如果不是本人操作请重置账号密码") preferredStyle:UIAlertControllerStyleAlert];
        XSWeakSelf;
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [weakSelf createUserTempData];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [(KAppDelegate) showLoginViewControllerWithStatuCodeNumber:statuCodelNum];
//            });
#warning [(KAppDelegate) showLoginViewControllerWithStatuCodeNumber:statuCodelNum]
#warning [(KAppDelegate) showLoginViewControllerWithStatuCodeNumber:statuCodelNum]
#warning [(KAppDelegate) showLoginViewControllerWithStatuCodeNumber:statuCodelNum]
#warning [(KAppDelegate) showLoginViewControllerWithStatuCodeNumber:statuCodelNum]
                
        }];
        //            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:confirm];
        //            [alert addAction:cancel];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[YSHelp getCurrentVC] presentViewController:alert animated:YES completion:nil];
        });
    }
    else{
//        [(KAppDelegate) showLoginViewControllerWithStatuCodeNumber:statuCodelNum];
    }
    
}

- (void)cancelAllOperations{
    [[afnManager operationQueue] cancelAllOperations];
}


- (void)createUserTempData{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString new] forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString new] forKey:@"WritemallToken"];
    
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSString new] forKey:@"AutoLoginNowDateKey"];
    //[[NSUserDefaults standardUserDefaults]setObject:[NSString new] forKey:@"fanChaoXieAccountKey"];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString new] forKey:@"fanChaoXiePwdKey"];
   
    
//        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cloudRootNodeID"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [SSUserManager sharedUser].isLoginSuccess = NO;
//            [[NSNotificationCenter defaultCenter] postNotificationName:KUserInfoLoginOutNotification object:nil];
    
    NSString*uuid=[CMUUIDManager readUUID];
    if(kStringIsEmpty(uuid)){
    uuid = [NSString new];
    }


    [SSUserManager sharedUser].userModel.mobile = [uuid copy];
}


-(id )fileData:(id)file{
//    NSData *imageData = [file TIFFRepresentation];
    NSData *imageData = UIImageJPEGRepresentation(file, 1.0);
    return imageData;
}

#pragma mark 下载地址文件不需要token
- (void)downLoadFileData:(NSString *)downLoadStr fileName:(NSString *)fileNameString fileExt:(NSString *)fileExtString
                          resultData:(void (^)(NSData *fileData,NSString *fileName,NSString *error))resultBk{

    NSLog(@"downLoadEvent\n");
//    NSMutableArray *tempMarr = [NSMutableArray new];
//    [tempMarr addObject:@{@"tempId":sender.docId}];
//
//
//    NSString *downLoadStr = [NSString stringWithFormat:@"%@%@",API_Images_BASEURL,sender.docId];

    NSDictionary *paramerDict = @{};
    NSLog(@"API_writerCkWord--paramerDict==%@\n",paramerDict);
//    XSWeakSelf;// [API_BASEURL stringByAppendingString:API_writerCkWord]


//    [MBProgressHUD showTipMessageInWindow:@"正在下载.."];

    NSLog(@"downLoadStr--downLoadStr==%@\n",downLoadStr);
//    XSWeakSelf;
    downLoadStr =[downLoadStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"downLoadStr--downLoadStr==%@\n",downLoadStr);
    //创建url
    NSURL *url = [NSURL URLWithString:downLoadStr];
    //创建网络请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:180];
    request.HTTPMethod = @"GET";
    //获得数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        NSDictionary *dict = [(NSHTTPURLResponse *)httpResponse allHeaderFields];
        NSLog(@"downLoadCellModolOneEvent--dict==%@\n",dict);
        NSLog(@"downLoadCellModolOneEvent--connectionError==%@\n",connectionError);
        NSString *finalFileNameStr = @"";
        BOOL isHaveFileName = NO;
        NSString *ContentStr2 = [dict objectForKey:@"Content-Disposition"];
        NSArray *contentArray = [ContentStr2 componentsSeparatedByString:@";"];
        if([contentArray isKindOfClass:[NSArray class]]){
            if(contentArray.count==2){
                NSString *filename2 = contentArray.lastObject;
                if([filename2 isKindOfClass:[NSString class]]){
                    NSArray *filenameArray = [filename2 componentsSeparatedByString:@"="];
                    if([filenameArray isKindOfClass:[NSArray class]]){
                        if(filenameArray.count==2){
                            NSString *tempFinalFileNameStr = filenameArray.lastObject;
                            if([tempFinalFileNameStr isKindOfClass:[NSString class]]&&tempFinalFileNameStr.length>0){
                                finalFileNameStr = tempFinalFileNameStr;
                                isHaveFileName = YES;
                            }
                        }
                    }
                }
            }
        }
//        Content-Type = image/jpeg;
        NSString *ContentTypeExtString = [dict objectForKey:@"Content-Type"];
        NSString *finalFileNameExt = @"";
        BOOL isHaveFileExt = NO;
        if(ContentTypeExtString.length>0){
            NSArray *ContentTypeExtArray = [ContentTypeExtString componentsSeparatedByString:@"/"];
            if([ContentTypeExtArray isKindOfClass:[NSArray class]]){
                if(ContentTypeExtArray.count==2){
                    finalFileNameExt = ContentTypeExtArray.lastObject;
                    isHaveFileExt = YES;
                }
            }
        }
        
        
        NSString *tempFileNameStr;
        if(httpResponse.statusCode==200){

//            sender.commentStatus = YES;
//            [weakSelf addTemplateRiZhi:sender];
//            if(isHaveFileName){
//                tempFileNameStr = finalFileNameStr;
//            }
            
            
            if(notNillStr(fileNameString)){
                tempFileNameStr = fileNameString;
                isHaveFileName = YES;
            }
            else{
                if(isHaveFileName){
                    tempFileNameStr = finalFileNameStr;
                    isHaveFileName = YES;
                }
            }
            
            if(notNillStr(tempFileNameStr)){
                
            }
            else{
                tempFileNameStr = [NSString stringWithFormat:@"temp-%@未命名",[NSString getCurrentFormatTimes]];
            }
            
            if(tempFileNameStr.pathExtension.length>0){
                
            }
            else{
                if(notNillStr(fileExtString)){
                    tempFileNameStr = [NSString stringWithFormat:@"%@.%@",tempFileNameStr,fileExtString];
                }
            }
            
            if(tempFileNameStr.pathExtension.length>0){
                
            }
            else{
                if(isHaveFileExt){
                    tempFileNameStr = [NSString stringWithFormat:@"%@.%@",tempFileNameStr,finalFileNameExt];
                }
            }
            
            if(tempFileNameStr.pathExtension.length>0){
                
            }
            else{
                if(isHaveFileExt){
                    tempFileNameStr = [NSString stringWithFormat:@"%@.%@",tempFileNameStr,@"docx"];
                }
            }
            
//            if(notNillStr(fileNameString)){
//
//                if(notNillStr(fileExtString)){
//                    tempFileNameStr = [NSString stringWithFormat:@"%@.%@",fileNameString,fileExtString];
//                }
//                else{
//                    tempFileNameStr = fileNameString;
//                    if(isHaveFileExt){
//                        tempFileNameStr = [NSString stringWithFormat:@"%@.%@",fileNameString,finalFileNameExt];
//                    }
//                }
//            }


//            if(kStringIsEmpty(tempFileNameStr)){
//                
//                if(isHaveFileExt){
//                    tempFileNameStr = [NSString stringWithFormat:@"temp-%@未命名.%@",[NSString getCurrentFormatTimes],finalFileNameExt];
//                }
//                else{
//                    tempFileNameStr = [NSString stringWithFormat:@"temp-%@未命名.docx",[NSString getCurrentFormatTimes]];
//                }
//            }
            NSLog(@"[tempFileNameStr urlDecodeString]==%@\n",[tempFileNameStr urlDecodeString]);
//            //创建储存路径将文件存入
//            NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
//            path = [path stringByAppendingPathComponent:[tempFileNameStr urlDecodeString]];
//            [data writeToFile:path atomically:YES];
//            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"文件已下载至%@",path]];
            
            resultBk(data,tempFileNameStr,nil);
        }
        else{
//            [MBProgressHUD showTipMessageInWindow:@"文件下载失败请稍后重试！"];
            resultBk(nil,nil,@"文件下载失败请稍后重试！");
        }
    }];
}

-(void)multiPartPost:(NSDictionary *)dicData{

    NSString *POST_BOUNDS = @"";
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.112:8080/TestSerlvet/interfaces"];
    NSMutableString *bodyContent = [NSMutableString string];
    for(NSString *key in dicData.allKeys){
        id value = [dicData objectForKey:key];
        [bodyContent appendFormat:@"--%@\r\n",POST_BOUNDS];
        [bodyContent appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        [bodyContent appendFormat:@"%@\r\n",value];
    }
    [bodyContent appendFormat:@"--%@--\r\n",POST_BOUNDS];
    NSData *bodyData=[bodyContent dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
    [request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",POST_BOUNDS] forHTTPHeaderField:@"Content-Type"];
    [request addValue: [NSString stringWithFormat:@"%zd",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:bodyData];
    NSLog(@"请求的长度%@",[NSString stringWithFormat:@"%zd",bodyData.length]);
    __autoreleasing NSError *error=nil;
    __autoreleasing NSURLResponse *response=nil;
    NSLog(@"输出Bdoy中的内容>>\n%@",[[NSString alloc]initWithData:bodyData encoding:NSUTF8StringEncoding]);
    NSData *reciveData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if(error){
        NSLog(@"出现异常%@",error);
    }else{
        NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
        if(httpResponse.statusCode==200){
            NSLog(@"服务器成功响应!>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);

        }else{
            NSLog(@"服务器返回失败>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);

        }

    }
}


- (void)wqWriteData:(NSString *)contentString withFileName:(NSString *)fNameStr{
    
    [YSHelp wqWriteData:contentString withFileName:fNameStr];
}


//- (void)startUploadTaskWithFileURL:(NSString *)URLString fileArr:(NSArray*)fileArr parameterDictionay:(NSDictionary *)parameterDict succeed:(void (^)(id data))succeed withProgress:(void(^)(double uploadPr,NSUInteger taskIdentifierInt))uploadProgre failure:(void (^)(NSDictionary *error))failure
// contentType:(NSString *)contentTypeStr
// withTaskIdentifier:(NSInteger)taskIdentifierInt
// 开始上传文件
#pragma mark - uni多文件上传及多文件取消  uni--fromdata上传多文件
- (void)startUploadTaskWithOption:(NSDictionary *)optionDict succeed:(void (^)(id data,NSUInteger taskIdentifierInt))succeed withProgress:(void(^)(double uploadPr,NSUInteger taskIdentifierInt))uploadProgre failure:(void (^)(NSDictionary *error,NSUInteger taskIdentifierInt))failure{
////    NSURLSessionDataTask *task = [afnManager uploadTaskWithRequest:request fromFile:fileURL progress:^(NSProgress * _Nonnull uploadProgress) {
////        
////    } completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
////        // 处理完成的代码
////    }];
////    [task resume];
////    [self.uploadTasks addObject:task];
//    
//    
//    __block NSString *tempURL = URLString;
//    [self setHttpsFileWithURL:URLString];
//     afnManager.requestSerializer.timeoutInterval = timeoutNum;
//    [afnManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//    NSMutableDictionary *headerDic = [NSMutableDictionary new];
////    [headerDic setValue:[CWUserDefaults GetUserTokenStr] forKey:@"Authorization"];
//    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
//    if (token) {
//        [afnManager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
//////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
//    }else{
//        if([SSUserManager sharedUser].userModel.tempToken){
//            token = [SSUserManager sharedUser].userModel.tempToken;
////            NSLog(@"API_memberPlaceOrder--访客token==%@\n",token);
////
//            [afnManager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
//        }
//    }
//    [headerDic setValue:token forKey:@"Authorization"];
//
//    NSURLSessionDataTask *tempTask = [afnManager POST:URLString parameters:parameterDict headers:headerDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        //根据当前系统时间生成图片名称
//        NSDate *date = [NSDate date];
//        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//        [formatter setDateFormat:@"yyyyMMddHHmmss"];
//        NSString *dateString = [formatter stringFromDate:date];
//        for (int i = 0; i < fileArr.count; i++) {
//            NSString *fileNmae = [NSString stringWithFormat:@"%@%d.png",dateString,i];
//            id tempFileData = fileArr[i];
//            
//            NSData *imageData = tempFileData;
//            if([tempFileData isKindOfClass:[UIImage class]]){
//                imageData = [self fileData:tempFileData];
//            }
//            
//            [formData appendPartWithFileData:imageData name:@"file" fileName:fileNmae mimeType:@"application/octet-stream"];
//        }
//        } progress:^(NSProgress * _Nonnull uploadProgress) {
//            double completedCount = uploadProgress.completedUnitCount;
//            double totalCount = uploadProgress.totalUnitCount;
//            double ProgressFinal = completedCount/totalCount;
//            if (completedCount/totalCount > 0.99f) {
//                //NSLog(@"上传完成");
//            }else{
//                //NSLog(@"上传进度 %.2lf",completedCount/totalCount*100);
//            }
//            uploadProgre(ProgressFinal,0);
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//            NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
//            NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
//
//            succeed(jsonData);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//            NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
//            NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
//            failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo});
//        }];
//    uploadProgre(0.0,tempTask.taskIdentifier);
//    
//    [self.uploadTasks addObject:tempTask];
    
    
    
    XSWeakSelf;
    
    
    // XLBaesNavigationController *currontVc = [SSUntil currentNC];
    
    NSString *fileNameStr = optionDict[@"filename"];
    if(kStringIsEmpty(fileNameStr)){
        fileNameStr = [NSString new];
    }
    
    NSString *hostUrlStr = optionDict[@"hostUrl"];
    if(kStringIsEmpty(hostUrlStr)){
        hostUrlStr = [NSString new];
    }
    
    NSString *fileLocalUrlStr = optionDict[@"fileLocalUrl"];
    if(kStringIsEmpty(fileLocalUrlStr)){
        fileLocalUrlStr = [NSString new];
    }
    
    NSString *tokenStr = optionDict[@"token"];
    if(kStringIsEmpty(tokenStr)){
        tokenStr = [NSString new];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:tokenStr forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // /var/mobile/Containers/Data/Application/B7DB01AE-7E8C-410A-9CB8-CFFEE739D88D/Documents/Pandora/apps/__UNI__9CB9BD6/www/wqchangeImageDataType/1719915907-origin-IMG_1931.PNG
    
    
        NSRange goalStrRange = [fileLocalUrlStr rangeOfString:@"/Pandora/"];
    NSString *goalDirStrLast = [fileLocalUrlStr substringFromIndex:goalStrRange.location];
    
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * goalFilePath = [docsdir stringByAppendingPathComponent:goalDirStrLast];//将需要创建的串拼接到后面
    
    NSData *fData = [NSData dataWithContentsOfFile:goalFilePath];
    
    [self wqWriteData:[NSString stringWithFormat:@"goalFilePath==%@  fData==%@  optionDict==%@",goalFilePath,fData,optionDict.description] withFileName:@"startUploadTaskWithOption--ppp"];
    //    NSString *fileName = @"hmt";
    //    //  确定需要上传的文件(假设选择本地的文件)
    //    NSURL *filePath = [[NSBundle mainBundle] URLForResource:fileName withExtension:@"png"];
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];// @{@"fileName":fileNameStr};
    // [parameters setValue:fileNameStr forKey:@"fileName"];
    
    if(optionDict.allKeys.count>0){
        
        NSArray *kArrs = optionDict.allKeys;
        
        for (NSString *tempKStr in kArrs) {
            NSString *tempVStr = [optionDict valueForKey:tempKStr];
            [parameters setValue:tempVStr forKey:tempKStr];
        }
    }
  
    [parameters removeObjectForKey:@"fileLocalUrl"];
    [parameters removeObjectForKey:@"file"];
    [parameters removeObjectForKey:@"token"];
    [parameters removeObjectForKey:@"hostUrl"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    if (token) {
        [manager.requestSerializer setValue:token  forHTTPHeaderField:@"Authorization"];
        ////        [manager.requestSerializer setValue:token  forHTTPHeaderFieldAction:@"Authorization"];
    }
 

    //申明请求的数据是json类型
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/xml"forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json"forHTTPHeaderField:@"Accept"];
    
//    afnManager.requestSerializer.accessibilityTextualContext
    // 设置请求的接收内容类型
    //申明返回的结果是二进制类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml", nil];
    
    
    
//    ,@"application/x-www-form-urlencoded", @"text/json", @"text/javascript", @"text/html", @"text/plain",@"multipart/form-data",@"image/png",@"application/pdf",@"application/octet-stream",@"application/msword",@"image/jpeg",@"message/rfc822",@"multipart/alternative",@"application/vnd.openxmlformats-officedocument.wordprocessingml.document",@"application/vnd.ms-excel",@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",@"application/x-gtar",@"application/x-gzip",@"application/java-archive",@"application/vnd.ms-powerpoint",@"application/vnd.openxmlformats-officedocument.presentationml.presentation",@"application/vnd.ms-works",@"application/x-compress",@"application/x-zip-compressed",@"image/gif",@"application/xml"
    
    
    //@"application/x-www-form-urlencoded"
    //@"multipart/form-data"
    NSString *fileStr = @"file";
    
    
    
    [self wqWriteData:[NSString stringWithFormat:@"parameters==%@",parameters.description] withFileName:@"wqUnistartUploadTaskWithFileURL--00"];
    
    // taskDescription
    //@{@"Authorization":token}
    NSString *taskIdentifierIntStr=nil;
    BOOL wqIsBreak = NO;
    NSInteger wqRandInt =  arc4random()%10000000+1;
    taskIdentifierIntStr = [NSString stringWithFormat:@"%ld",wqRandInt];
    
    @synchronized (self) {
        while (!wqIsBreak) {
            BOOL wqIsContain = NO;
            for (NSURLSessionDataTask *tempDataTask in self.uploadTasks) {
                NSString *tempIdtfStr = tempDataTask.taskDescription;
                if([tempIdtfStr isEqualToString:taskIdentifierIntStr]){
                    wqIsContain = YES;
                }
            }
            if(wqIsContain){
                wqRandInt =  arc4random()%10000000+1;
                taskIdentifierIntStr = [NSString stringWithFormat:@"%ld",wqRandInt];
            }
            else{
                wqIsBreak = YES;
            }
        }
    }
    
    
    NSURLSessionDataTask *tempTask = [manager POST:hostUrlStr parameters:parameters headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //        Extension MIME Type
        //        .doc      application/msword
        //        .dot      application/msword
        //
        //        .docx     application/vnd.openxmlformats-officedocument.wordprocessingml.document
        //        .dotx     application/vnd.openxmlformats-officedocument.wordprocessingml.template
        // .ppt      application/vnd.ms-powerpoint
        
        //        文件流
        //        application/octet-stream：这是应用程序文件的默认值。
        
        
        /**
         *  appendPartWithFileURL   //  指定上传的文件
         *  fileStr                    //  指定在服务器中获取对应文件或文本时的key
         *  fileName                //  指定上传文件的原始文件名
         *  mimeType                //  指定商家文件的MIME类型
         */
        //[formData appendPartWithFileURL:filePath name:@"file" fileName:[NSString stringWithFormat:@"%@.png",fileName] mimeType:@"image/png" error:nil];
        //        [formData appendPartWithFileData:fData name:@"file" fileName:fileNameStr mimeType:@"application/docx"];
        //NSString *fileStr = @"file";
        
        
        //@"application/octet-stream"
        [formData appendPartWithFileData:fData name:fileStr fileName:fileNameStr mimeType:@"image/png"];
        //
        //
        //        // formData 将要上传的数据
        //                UIImage *image =[UIImage imageNamed:@"123"];
        //                NSData *data =UIImagePNGRepresentation(image);
        //                // 方法一
        //                /**
        //                  data:上传文件二进制数据
        //                  name:接口的名字
        //                  fileName:文件上传到服务器之后叫什么名字
        //                  mineType:上传文件的类型，application/octet-stream可以上传任意二进制mineType.
        //                 */
        //                [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
        //                // 方法二
        //                /**
        //                 data:上传文件二进制数据
        //                 name:接口的名字
        //                 这种方法内部会将文件名当做上传到服务器之后的名字，并自动获取其类型
        //                 */
        //                [formData appendPartWithFormData:fData name:@"file"];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        double completedCount = uploadProgress.completedUnitCount;
        double totalCount = uploadProgress.totalUnitCount;
        double ProgressFinal = completedCount/totalCount;
//        if (completedCount/totalCount > 0.99f) {
//            //NSLog(@"上传完成");
//        }else{
//            //NSLog(@"上传进度 %.2lf",completedCount/totalCount*100);
//        }
        if(ProgressFinal<1.0){
            uploadProgre(ProgressFinal,[taskIdentifierIntStr integerValue]);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *resultDict = responseObject;
        if([resultDict isKindOfClass:[NSData class]]){
            NSData *tempResDtata = (NSData *)resultDict;
            NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:tempResDtata options:NSJSONReadingMutableContainers error:nil];
            if(jsonData!=nil){
                resultDict = jsonData;
            }
            else{
                NSData *tempResDtata = (NSData *)resultDict;
                NSString * jsonStr = [[NSString alloc]initWithData:tempResDtata encoding:NSUTF8StringEncoding];
                
                [self wqWriteData:[NSString stringWithFormat:@"resultDict==%@ taskIdentifierInt==%ld    jsonStr==%@",resultDict.description,[taskIdentifierIntStr integerValue],jsonStr] withFileName:@"wqUnistartUploadTaskWithFileURL--00111"];
                
                NSData * data12 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
                
                
                
                NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data12 options:NSJSONReadingMutableContainers error:nil];
                
                NSString *wqclassStr;
                if([responseObject isKindOfClass:[NSData class]]){
                    wqclassStr = @"NSData";
                    //[weakSelf parseXMLStringData:responseObject];
                }
                else if([responseObject isKindOfClass:[NSDictionary class]]){
                    wqclassStr = @"NSDictionary";
                }
                [self wqWriteData:[NSString stringWithFormat:@"resultDict==%@ taskIdentifierInt==%ld    jsonStr==%@  data12==%@ jsonData==%@    wqclassStr==%@",resultDict.description,[taskIdentifierIntStr integerValue],jsonStr,data12,jsonData.description,wqclassStr] withFileName:@"wqUnistartUploadTaskWithFileURL--00111"];
                
                if(jsonData!=nil){
                    resultDict = jsonData;
                }
                else{
                    resultDict = [NSDictionary new];
                }
                
            }
            
        }
        [self wqWriteData:[NSString stringWithFormat:@"resultDict==%@ taskIdentifierInt==%ld",resultDict.description,[taskIdentifierIntStr integerValue]] withFileName:@"wqUnistartUploadTaskWithFileURL--00111"];
//        NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
//        NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];

        succeed(resultDict,[taskIdentifierIntStr integerValue]);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self wqWriteData:[NSString stringWithFormat:@"tempTask.taskDescription==%ld    error==%@",[taskIdentifierIntStr integerValue],error.description] withFileName:@"wqUnistartUploadTaskWithFileURL--00111222"];
        
        NSString *errorInfo = [error userInfo][@"NSLocalizedDescription"];
        NSString *errorUrlKey = [error userInfo][@"NSErrorFailingURLKey"];
        failure(@{@"NSErrorFailingURLKey":errorUrlKey,@"NSLocalizedDescription":errorInfo},[taskIdentifierIntStr integerValue]);
    }];
    
    tempTask.taskDescription = taskIdentifierIntStr;
    
    
    [self wqWriteData:[NSString stringWithFormat:@"tempTask.taskDescription==%ld tempTask.class==%p",[taskIdentifierIntStr integerValue],tempTask] withFileName:@"wqUnistartUploadTaskWithFileURL--tempTask.taskIdentifier00111222"];
    uploadProgre(0.0,[taskIdentifierIntStr integerValue]);

    [self.uploadTasks addObject:tempTask];
}
 
// 取消特定的上传任务
#pragma mark - uni 取消特定的上传任务
- (void)cancelUploadTaskAtIndex:(NSUInteger)taskIdentifierInt {
    //NSURLSessionDataTask *task = self.uploadTasks[taskIdentifierInt];
    
    for (NSURLSessionDataTask *task in self.uploadTasks) {
        if([task.taskDescription integerValue] == taskIdentifierInt){
            [task cancel]; // 取消任务
            [self.uploadTasks removeObjectAtIndex:taskIdentifierInt]; // 从数组中移除已取消的任务
            break;
        }
    }
}
 
// 取消所有上传任务
#pragma mark - uni 取消所有上传任务
- (void)cancelAllUploadTasks {
    for (NSURLSessionDataTask *task in self.uploadTasks) {
        [task cancel];
    }
    [self.uploadTasks removeAllObjects];
}

- (NSMutableArray *)uploadTasks{
    if(!_uploadTasks){
        _uploadTasks = [[NSMutableArray alloc] init];
    }
    return _uploadTasks;
}


- (void)parseXMLStringData:(NSData *)xmlStringData {
//    NSData *xmlStringData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlStringData];
    parser.delegate = self;
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    
    if(!self.currentElementValue){
        // 初始化元素值
        self.currentElementValue = [[NSMutableString alloc] init];
    }
    [self wqWriteData:[NSString stringWithFormat:@"%@   self.currentElementValue==%@",@"didStartElement",self.currentElementValue] withFileName:@"didStartElement"];
}
 
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    // 找到元素的字符
    [self.currentElementValue appendString:string];
}
 
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    // 完成元素解析
    if (self.currentElementValue.length > 0) {
        // 这里处理解析到的元素内容
        NSLog(@"Element: %@, Value: %@", elementName, self.currentElementValue);
        
        
        [self wqWriteData:[NSString stringWithFormat:@"%@   self.currentElementValue==%@",@"didEndElement",self.currentElementValue] withFileName:@"didEndElement"];
    }
}
 
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    // 错误处理
    NSLog(@"Parse error: %@", parseError);
}
@end

//  // 获取Bundle数据
//1.第一种方法
//NSString *path = [[NSBundle mainBundle] pathForResource:@"myBundle" ofType:@"bundle"];
//NSBundle *bundle = [NSBundle bundleWithPath:path];
//NSString *file = [bundle pathForResource:@"pic" ofType:@"png"];
//UIImage *img = [UIImage imageWithContentsOfFile:file];

//2.第二种方法
//NSString *file2 = [[NSBundle mainBundle] pathForResource:@"myBundle.bundle/pic" ofType:@"png"];
//UIImage *img2 = [UIImage imageWithContentsOfFile:file2];

//3.第三种方法
//UIImage *img3 = [UIImage imageNamed:@"myBundle.bundle/pic"];
